import { defineStore } from 'pinia'
import { Names } from './store-name'
import { ref } from "vue"


//options 选项式API
export const useUserStore = defineStore(Names.USER, {
  //data： 类似于组件中的data
  state: () => {
    return {
      name: "张三",
      age: 20
    }
  },

  //computed 修饰一些值
  getters: {
  },
  //methods 可以做同步、异步，提交state
  actions: {
    setNameAndAge(name: string, age: number) {
      this.name = name
      this.age = age
    }
  },

  //持久化开启
  persist: true

})


type Student = {
  name: string,
  grade: number
}


//模拟登陆时，2秒后获取到student的值
const loginUser = (): Promise<Student> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: "小明",
        grade: 3
      })
    }, 2000)
  })
}

// actions中方法互调
// 当name参数有值时，就更新，否则使用登陆查询的值
export const useStudentStore = defineStore("student", {
  state: () => {
    return {
      student: <Student>{ name: "张三" }
    }
  },
  getters: {
    getFullName(): string {
      console.log("getFullName 被调用了")
      return `${this.student.name}大学${this.student.grade}年级`
    },
    getFullName2(state) {
      console.log("getFullName2 被调用了")
      return state.student.name + "大学" + state.student.grade + "年级"
    },
    getFullName3: (state) => {
      console.log("getFullName3 被调用了")
      return (firstName: string) => firstName + "-" + state.student.name
    }
  },
  actions: {
    async setStudent(name: string | null) {
      this.student = await loginUser()
      this.updateStudent(name)
    },
    updateStudent(name: string | null) {
      if (name) {
        this.student.name = name
      }
    }
  },

  //持久化，并自定义key
  persist: {
    key: "my-custom-key",
    storage: localStorage,  //sessionStorage,localStorage,
  }
})


//setup store 组合式API
export const useSystemStore = defineStore(Names.SYSTEM, () => {

  const systemInfo = ref({ version: "win10" })

  function getMemory() {
    return "16G"
  }

  return { systemInfo, getMemory }

},
  {
    //持久化，并自定义key
    persist: {
      storage: sessionStorage,  //sessionStorage,localStorage,
    }
  }
)